#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import random
from app import db
from .model import User
from flask_restful import Resource
from flask_login import login_user, logout_user, current_user
from app.authentication import restfulApi, auther
from flask import render_template, request, redirect, url_for, session, make_response


@auther.route('/')
def loginindex():
    return render_template('/authentication/login.html')


@auther.route('/register')
def register():
    return render_template('/authentication/reg.html')


@auther.route('/changepass')
def password():
    return render_template('/authentication/password.html')


from PIL import Image, ImageFont, ImageDraw, ImageFilter
from io import BytesIO


def validate_picture(width=130, heigth=50):
    # 生成一个临时随机的字符串
    nonce = ''.join([random.choice([chr(random.randrange(97, 122)), str(random.randint(0, 9)),
                                    chr(random.randrange(65, 90))]) for i in range(5)])
    # 生成一个图片对象    颜色， (宽，高), 颜色 三色随机
    imgobj = Image.new('RGB', (width, heigth), color=tuple([random.randint(0, 255) for i in range(3)]))
    draw = ImageDraw.Draw(imgobj)   # 创建draw对象

    font = ImageFont.truetype('/static/font/msyh.ttf', size=30)  # 设置字体， 字体大小
    draw.text((10, 4), text=nonce, fill='black', font=font)  # 用画笔在板子上画出来,

    # 划几根干扰线
    for num in range(8):
        x1 = random.randint(0, width / 2)
        y1 = random.randint(0, heigth / 2)
        x2 = random.randint(0, width)
        y2 = random.randint(heigth / 2, heigth)
        draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

    # 模糊下,加个帅帅的滤镜～
    im = imgobj.filter(ImageFilter.FIND_EDGES)
    return im, nonce


@auther.route('/validate_code')
def validate_code():
    image, nonce = validate_picture()
    buf = BytesIO()
    image.save(buf, 'jpeg')
    # 读取写入后的二进制文件
    data = buf.getvalue()
    # 把二进制作为response发回前端，并设置首部字段
    response = make_response(data)
    response.headers['Content-Type'] = 'image/jpeg'
    # 添加session, 在session中在次进行判断
    session['image'] = nonce
    return response


class Login(Resource):
    def post(self):
        '''
            状态码  10000： 表示已激活 可以登陆
                    10001:  帐号或密码错误
                    10002： 没有激活
                    10003： 验证码不对
        # 1、检查用户是否存在
        # 2、检查用户是否激活，没有就直接 return
        # 3、如果正常返回url
        '''
        print(session)
        res = {'code': 10001}  # 直接判断不存在
        logdic = request.form.to_dict()  # 获取字典
        username = User.query.filter_by(name=logdic["name"]).first()
        if username:
            if username.is_active:
                if session.get('image'):
                    if session.get('image').lower() == logdic["vercode"].lower():
                        print(session.get('image'))
                        print(logdic["vercode"])
                        if username.verify_password(logdic["password"]):
                            login_user(username)
                            session['name'] = logdic['name']
                            res["url"] = request.args.get('next') or url_for("backend.index")
                            res["code"] = 10000
                    else:
                        res["code"] = 10003
            else:
                res["code"] = 10002
        return res


class RegisterApi(Resource):
    def post(self):
        res = {'code': 10000}
        regdic = request.form.to_dict()
        del regdic["repass"]
        if User.query.filter_by(email=regdic['email']).first():
            res["code"] = 10002
        elif User.query.filter_by(name=regdic["name"]).first():
            res["code"] = 10001
        else:
            instance = User(**regdic)
            db.session.add(instance)
            db.session.commit()
        return res

    def put(self):
        '''
            10000:  通过
            10001： 用户没有登陆
            10002： 密码检验失败
        '''
        res = {"code": 10001}
        regdic = request.form.to_dict()
        # 如果用户登陆， 那么才让它执行修改操作
        if current_user.is_authenticated:
            # 如果这个用户密码检验通过了才执行下一步
            getuser = User.query.get(session.get('user_id'))
            if getuser.verify_password(regdic["oldpassword"]):
                getuser.password = regdic["newpassword"]
                db.session.add(getuser)
                db.session.commit()
                res["code"] = 10000
            else:
                res["code"] = 10002
        return res


@auther.route('/logout')
def logout():
    session.pop('name')
    logout_user()  # 包含了 sessin.pop
    return redirect(url_for('auther.loginindex'))


restfulApi.add_resource(RegisterApi, '/registerApi', endpoint="RegisterApi")
restfulApi.add_resource(Login, '/userLogin', endpoint="login")
